import React from 'react';
import './ToduList.scss';
import { useState, useEffect } from 'react';
import ToduListFm from './ToduListFm';
import ToduListTb from './ToduListTb';
import contextData from '../context/contextData';
export default function ToduList() {
  // 表格数据
  const [dataList, setDataList] = useState([]);
  // 获取列表数据
  const getList = () => {
    setDataList(
      [
        {
          title: '标题1',
          email: '2002/2/5',
          priority: 10,
          key: '1',
        },
        {
          title: '标题2',
          email: '2502/2/5',
          priority: 5,
          key: '2',
        },
      ].sort(compare)
    );
  };
  useEffect(() => {
    getList();
  }, []);
  // 获取子组件传递的数据
  const onAdd = (data) => {
    setDataList(() => {
      return [...dataList, data].sort(compare);
    });
  };
  //比较函数 正
  const compare = function (x, y) {
    if (x.priority < y.priority) {
      return -1;
    } else if (x.priority > y.priority) {
      return 1;
    } else {
      return 0;
    }
  };
  //比较函数 反
  const compare1 = function (x, y) {
    if (x.priority < y.priority) {
      return 1;
    } else if (x.priority > y.priority) {
      return -1;
    } else {
      return 0;
    }
  };
  // 正序倒序
  const onSort = (str) => {
    if (str === '正') {
      setDataList(() => {
        return [...dataList].sort(compare);
      });
      return false;
    }
    // 反
    setDataList(() => {
      return [...dataList].sort(compare1);
    });
  };
  // 删除
  const onDelete = (index) => {
    setDataList(() => {
      return dataList.filter((i, key) => i.email !== index);
    });
  };
  return (
    <div className="todolist-container">
      <contextData.Provider value={{ dataList, onAdd, onSort, onDelete }}>
        <header>
          <ToduListFm />
        </header>
        <section>
          <h2>列表</h2>
          <ToduListTb />
        </section>
      </contextData.Provider>
    </div>
  );
}
